package com.xuerhua.yxt.controller.teacher;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.xuerhua.yxt.common.AppUser;
import com.xuerhua.yxt.common.Const;
import com.xuerhua.yxt.common.MenuConst;
import com.xuerhua.yxt.common.RspResult;
import com.xuerhua.yxt.common.enums.InterestCourseStatus;
import com.xuerhua.yxt.common.enums.Status;
import com.xuerhua.yxt.controller.BaseController;
import com.xuerhua.yxt.model.ClassTeachers;
import com.xuerhua.yxt.model.Grid;
import com.xuerhua.yxt.model.InterestCourseStudentSign;
import com.xuerhua.yxt.model.ReqInterestCourseChange;
import com.xuerhua.yxt.model.StudentInfo;
import com.xuerhua.yxt.page.OrderBy;
import com.xuerhua.yxt.page.Page;
import com.xuerhua.yxt.reqVo.BaseQueryVO;
import com.xuerhua.yxt.reqVo.InterestCourseQueryVO;
import com.xuerhua.yxt.reqVo.InterestCourseReqVO;
import com.xuerhua.yxt.reqVo.ReqInterestCourseQueryVO;
import com.xuerhua.yxt.service.IClassTeachersService;
import com.xuerhua.yxt.service.IInterestCourseInfoService;
import com.xuerhua.yxt.service.IStudentService;
import com.xuerhua.yxt.service.ITeacherService;
import com.xuerhua.yxt.utils.StringUtil;
import com.xuerhua.yxt.view.InterestCourseView;
import com.xuerhua.yxt.view.ReqInterestCourseView;

@RequestMapping(Const.TEACHER_ROLE + MenuConst.INTEREST_COURSE)
@Controller
public class InterestCourseController extends BaseController {

	private Logger logger = LoggerFactory.getLogger(InterestCourseController.class);
	
	@Autowired
	private ITeacherService teacherService;
	@Autowired
	private IInterestCourseInfoService interestCourseInfoService;
	@Autowired
	private IClassTeachersService classTeachersService;
	@Autowired
	private IStudentService studentService;
	
	@RequestMapping(value={"","/"})
	public String index(Model model) {
		AppUser appUser = getAppUser();
		if(StringUtil.isExistPosition("5,3002,3003", appUser.getTeacher().getPosition())){
			model.addAttribute("isAdmin", true);
		}
		model.addAttribute("isClassTeacher", teacherService.
				isClassTeacher(appUser.getTeacher().getId(), getCurrentTerm().getFinishYear()));
		model.addAttribute("isTeachingTeacher", interestCourseInfoService.
				isTeachingTeacher(appUser.getTeacher().getId()));
		return "interestCourse/index";
	}
	
	@RequestMapping("list")
	public String list(Model model) {
		AppUser appUser = getAppUser();
		if(StringUtil.isExistPosition("5,3002,3003", appUser.getTeacher().getPosition())) {
			model.addAttribute("isAdmin", true);
		}
		return "interestCourse/list";
	}
	
	@RequestMapping("detail/{courseId}")
	public String detail(Model model, @PathVariable Integer courseId) {
		AppUser appUser = getAppUser();
		if(StringUtil.isExistPosition("5,3002,3003", appUser.getTeacher().getPosition())) {
			model.addAttribute("isAdmin", true);
		}
		BaseQueryVO vo = new BaseQueryVO();
		vo.setId(courseId);
		vo.setTermId(getCurrentTerm().getId());
		model.addAttribute("detail", interestCourseInfoService.selectViewById(vo));
		return "interestCourse/detail";
	}
	
	@RequestMapping("detail/edit/{courseId}")
	public String editDetail(Model model, @PathVariable Integer courseId){
		AppUser appUser = getAppUser();
		if(!StringUtil.isExistPosition("5,3002,3003", appUser.getTeacher().getPosition())) {
			return null;
		}
		model.addAttribute("courseId", courseId);
		return "interestCourse/edit";
	}
	@RequestMapping("addCourse")
	public String addCourse(Model model) {
		AppUser appUser = getAppUser();
		if(!StringUtil.isExistPosition("5,3002,3003", appUser.getTeacher().getPosition())) {
			return null;
		}
		model.addAttribute("courseId", null);
		return "interestCourse/edit";
	}
	/**
	 * 我的班级
	 * @param vo
	 * @return
	 */
	@RequestMapping("myClass")
	public String myClass() {
		return "interestCourse/myClass";
	}
	/**
	 * 家长调班申请
	 * @return
	 */
	@RequestMapping("changeClass")
	public String changeClass() {
		return "interestCourse/changeClass";
	}
	/**
	 * 老师任教课程
	 * @return
	 */
	@RequestMapping("teachingCourse")
	public String teachingCourse(Model model) {
		AppUser appUser = getAppUser();
		BaseQueryVO vo = new BaseQueryVO();
		vo.setId(appUser.getTeacher().getId());
		vo.setTermId(getCurrentTerm().getId());
		List<InterestCourseView> list = interestCourseInfoService.selectViewForTeaching(vo);
		model.addAttribute("list", list);
		return "interestCourse/teachingCourse";
	}
	
	@RequestMapping("signed/list")
	@ResponseBody Object signedList(InterestCourseQueryVO vo) {
		AppUser appUser = getAppUser();
		vo.setSchoolId(appUser.getTeacher().getSchoolId());
		vo.setTermId(getCurrentTerm().getId());
		vo.setTeacherId(appUser.getTeacher().getId());
		return interestCourseInfoService.selectSignedListForClass(vo);
	}
	
	@RequestMapping("noSign/list")
	@ResponseBody Object noSignedList(InterestCourseQueryVO vo) {
		AppUser appUser = getAppUser();
		vo.setSchoolId(appUser.getTeacher().getSchoolId());
		vo.setTermId(getCurrentTerm().getId());
		vo.setGrade(appUser.getTeacher().getGrade());
		vo.setTeacherId(appUser.getTeacher().getId());
		return interestCourseInfoService.selectNoSignListForClass(vo);
	}
	
	@RequestMapping("list/query")
	@ResponseBody Object listQuery(BaseQueryVO vo) {
		String nt = request.getParameter("nt");
		vo.setTermId(getCurrentTerm().getId()); 
		vo.setFinishYear(getCurrentTerm().getFinishYear());
		if(StringUtils.isNotBlank(nt)) {
			if(nt.equals("edit")) return interestCourseInfoService.selectList(vo);
			return interestCourseInfoService.selectViewList(vo);
		}else {
			AppUser appUser = getAppUser();
			vo.setId(appUser.getTeacher().getId());
			ClassTeachers classTeachers = classTeachersService.selectByClassTeacherId(vo);
			vo.setClazz(classTeachers.getClazz());
			vo.setGrade(classTeachers.getGrade());
			return interestCourseInfoService.selectViewListForClass(vo);
		}
	}
	
	@RequestMapping("detail/query")
	@ResponseBody Object detailQuery(Integer courseId) {
		BaseQueryVO vo = new BaseQueryVO();
		vo.setId(courseId);
		vo.setTermId(getCurrentTerm().getId());
		return interestCourseInfoService.selectViewById(vo);
	}
	
	@RequestMapping("addUpdate")
	@ResponseBody Object addUpdate(InterestCourseReqVO vo) {
		try {
			interestCourseInfoService.addAndUpdate(vo);
			return new RspResult(Status.SUCCESS);
		} catch (Exception e) {
			logger.error("---addUpdate error={}", e);
		}
		return new RspResult(Status.FAIL);
	}
	
	@RequestMapping("signSubmit")
	@ResponseBody Object signSubmit(InterestCourseStudentSign record) {
		try {
			record.setTermId(getCurrentTerm().getId());
			interestCourseInfoService.insertSign(record);
			return new RspResult(Status.SUCCESS);
		} catch (Exception e) {
			logger.error("---signSubmit error={}", e);
		}
		return new RspResult(Status.FAIL);
	}
	@RequestMapping("changeSubmit")
	@ResponseBody Object changeSubmit(ReqInterestCourseChange record) {
		try {
			AppUser appUser = getAppUser();
			record.setSchoolId(appUser.getTeacher().getSchoolId());
			record.setTermId(getCurrentTerm().getId());
			record.setApplyerId(appUser.getTeacher().getId());
			ReqInterestCourseQueryVO ricVo = new ReqInterestCourseQueryVO();
			ricVo.setTermId(getCurrentTerm().getId());
			ricVo.setStudentId(record.getStudentId());
			ricVo.setStatus(InterestCourseStatus.AUDIT_SUCCESS.getCode());
			int changeCount = interestCourseInfoService.selectCountForStudent(ricVo);
			if(changeCount >= 2) {
				return new RspResult(Status.COURSE_CHANGE_FULL);
			}
			BaseQueryVO vo = new BaseQueryVO();
			vo.setTermId(getCurrentTerm().getId());
			vo.setId(record.getNewCourseId());
			if(interestCourseInfoService.isFullForCourseId(vo)) {
				return new RspResult(Status.COURSE_FULL);
			}
			StudentInfo student = studentService.selectById(record.getStudentId());
			if(student == null) {
				return new RspResult(Status.EXPIRED_DATA);
			}
			record.setStatus(InterestCourseStatus.AUDIT_SUCCESS.getCode());
			record.setStudentName(student.getName());
			record.setApplyerId(appUser.getTeacher().getId());
			record.setAuditTeacher(appUser.getTeacher().getName());
			record.setAuditTeacherId(appUser.getTeacher().getId());
			record.setUpdateTime(new Date());
			interestCourseInfoService.addChangeCourseReqByTeacher(record);
			return new RspResult(Status.SUCCESS);
		} catch (Exception e) {
			logger.error("---changeSubmit error={}", e);
		}
		return new RspResult(Status.FAIL);
	}
	
	@RequestMapping("changeClass/pending")
	@ResponseBody Object changeClassPending(ReqInterestCourseQueryVO vo) {
		AppUser appUser = getAppUser();
		vo.setTeacherId(appUser.getTeacher().getId());
		vo.setTermId(getCurrentTerm().getId());
		return interestCourseInfoService.selectPendingReqList(vo);
	}
	
	@RequestMapping("changeClass/audied")
	@ResponseBody Object changeClassAudied(ReqInterestCourseQueryVO vo) {
		try {
			AppUser appUser = getAppUser();
			vo.setTermId(getCurrentTerm().getId());
			vo.setTeacherId(appUser.getTeacher().getId());
			Page<ReqInterestCourseView> page = new Page<ReqInterestCourseView>();
			Grid grid = new Grid();
			List<OrderBy> sorts = new ArrayList<>();
			sorts.add(new OrderBy("updateTime", "desc"));
			page.setSorts(sorts);
			page.setParams(vo);
			page.setPageNo(vo.getPage());
			page.setPageSize(vo.getRows());
			List<ReqInterestCourseView> list = interestCourseInfoService.selectAuditedReqList(page);
			grid.setRows(list);
			grid.setTotal(page.getTotalRecord());
			return grid;
		} catch (Exception e) {
			logger.error("---auditedList error={}", e);
		}
		return null;
	}
	
	@RequestMapping("audit/success")
	@ResponseBody Object auditSuccess(ReqInterestCourseChange record) {
		try {
			record.setStatus(InterestCourseStatus.AUDIT_SUCCESS.getCode());
			AppUser appUser = getAppUser();
			record.setAuditTeacher(appUser.getTeacher().getName());
			record.setAuditTeacherId(appUser.getTeacher().getId());
			interestCourseInfoService.updateAuditByClassTeacher(record);
			return new RspResult(Status.SUCCESS);
		} catch (Exception e) {
			logger.error("---auditSuccess error={}", e);
		}
		return new RspResult(Status.FAIL);
	}
	
	@RequestMapping("audit/reject")
	@ResponseBody Object auditReject(ReqInterestCourseChange record) {
		try {
			record.setStatus(InterestCourseStatus.AUDIT_REJECT.getCode());
			AppUser appUser = getAppUser();
			record.setAuditTeacher(appUser.getTeacher().getName());
			record.setAuditTeacherId(appUser.getTeacher().getId());
			interestCourseInfoService.updateAuditByClassTeacher(record);
			return new RspResult(Status.SUCCESS);
		} catch (Exception e) {
			logger.error("---auditReject error={}", e);
		}
		return new RspResult(Status.FAIL);
	}
	
	@RequestMapping("teachingCourse/stuList")
	@ResponseBody Object teachingCourseStuList(InterestCourseQueryVO vo) {
		try {
			AppUser appUser = getAppUser();
			vo.setTeacherId(appUser.getTeacher().getId());
			vo.setTermId(getCurrentTerm().getId());
			return interestCourseInfoService.selectSignListForTeachingByCourseId(vo);
		} catch (Exception e) {
			logger.error("--teachingCourseList error={}", e);
		}
		return null;
	}
	
}
